<template>
  <form>
    <table>
      <thead>
        <tr>
          <th>新增和修改的页面</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <input type="text" placeholder="请输入书名" v-model="formData.bookName" />
          </td>
        </tr>
        <tr>
          <td>
            <input type="text" placeholder="请输入作者" v-model="formData.author" />
          </td>
        </tr>
        <tr>
          <td>
            <input type="text" placeholder="简介" v-model="formData.about" />
          </td>
        </tr>
        <tr>
          <td>
            <input type="button" value="保存" @click="btnSave()" />
            <input type="button" value="取消" @click="btnCancel()" />
          </td>
        </tr>
      </tbody>
    </table>
  </form>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { onMounted, ref } from 'vue'
import { addBook, getById, editBook } from '@/api/bookApi'


let formData = ref({
    bookName: '',
    author: '',
    about:'',

})


let router = useRouter()
let route = useRoute()

async function btnSave() {
    let id = route.params.id || 0
    // 如果id大于0，说明是编辑后的保存，调用put，反之则是新增，需要调用post
    let res;
    if (id > 0) {
        res = await editBook(id, formData.value)
    } else {
        res = await addBook(formData.value)
    }
    console.log('保存');
    // 拿到表单数据，向后端发请求，拿到后端返回的响应数据，再来处理响应

    console.log(res);
    if (res.code = 1000) {
        router.push('/')
    } else {
        console.log(
            res.msg
        );
    }


}

function btnCancel() {
    router.push('/')
}


onMounted(async () => {
    // 从路由中拿id，并向后端发请求，拿到响应数据后，将数据渲染给表单
    let id = route.params.id || 0;
    console.log('编辑页的Id', id);
    // 当有id时，说明其是编辑，需要发请求，从后端拿数据，并且拿不对劲数据后渲染给表单
    if (id > 0) {
        let res = await getById(id);
        formData.value.bookName = res.data.bookName;
        formData.value.author = res.data.author;
        formData.value.about=res.data.about;
    }
})
</script>